import { FishModeService } from '../services/fishModeService';

// 全局变量声明
declare global {
    interface Window {
        fishModeService: FishModeService;
    }
}

// 初始化服务
let fishModeService: FishModeService;

// Office.js 初始化
Office.onReady(async () => {
    try {
        fishModeService = FishModeService.getInstance();
        await fishModeService.initialize();
        
        // 将服务实例暴露到全局，供命令函数使用
        window.fishModeService = fishModeService;
        
        console.log('Commands initialized');
    } catch (error) {
        console.error('Failed to initialize commands:', error);
    }
});

// 切换摸鱼模式命令
async function toggleFishMode(event: Office.AddinCommands.Event): Promise<void> {
    try {
        const isActive = fishModeService.toggleFishMode();
        
        // 显示通知
        await showNotification(
            isActive ? '🐠 摸鱼模式已启用' : '📝 正常模式已启用',
            isActive ? 'info' : 'info'
        );
        
        // 完成事件处理
        event.completed();
        
    } catch (error) {
        console.error('Error toggling fish mode:', error);
        await showNotification('切换模式失败', 'error');
        event.completed();
    }
}

// 显示通知函数
async function showNotification(message: string, type: string): Promise<void> {
    try {
        // 在Word中显示信息栏通知
        await Word.run(async (context) => {
            // 插入临时文本作为反馈
            const selection = context.document.getSelection();
            
            // 临时显示状态信息
            selection.insertText(`[${message}]`, Word.InsertLocation.after);
            await context.sync();
            
            // 1秒后删除状态信息
            setTimeout(async () => {
                try {
                    await Word.run(async (ctx) => {
                        const newSelection = ctx.document.getSelection();
                        // 这里可以实现更智能的状态信息清除逻辑
                        await ctx.sync();
                    });
                } catch (cleanupError) {
                    console.log('Status cleanup completed');
                }
            }, 1500);
        });
    } catch (error) {
        console.error('Error showing notification:', error);
    }
}

// 重置进度命令
async function resetProgress(event: Office.AddinCommands.Event): Promise<void> {
    try {
        await fishModeService.reset();
        await showNotification('📚 阅读进度已重置', 'info');
        event.completed();
    } catch (error) {
        console.error('Error resetting progress:', error);
        await showNotification('重置失败', 'error');
        event.completed();
    }
}

// 获取当前状态命令
async function getCurrentStatus(event: Office.AddinCommands.Event): Promise<void> {
    try {
        const state = fishModeService.getState();
        const status = `模式: ${state.isActive ? '摸鱼' : '正常'} | 进度: ${state.readCharacters}/${state.totalCharacters}`;
        await showNotification(status, 'info');
        event.completed();
    } catch (error) {
        console.error('Error getting status:', error);
        event.completed();
    }
}

// 导出函数供Office.js调用
(global as any).toggleFishMode = toggleFishMode;
(global as any).resetProgress = resetProgress;
(global as any).getCurrentStatus = getCurrentStatus;

// 注册全局快捷键处理
document.addEventListener('keydown', (event) => {
    // Ctrl + Shift + F: 切换摸鱼模式
    if (event.ctrlKey && event.shiftKey && event.key === 'F') {
        event.preventDefault();
        if (fishModeService) {
            fishModeService.toggleFishMode();
        }
    }
    
    // Ctrl + Shift + R: 重置进度
    if (event.ctrlKey && event.shiftKey && event.key === 'R') {
        event.preventDefault();
        if (fishModeService) {
            fishModeService.reset();
        }
    }
    
    // Ctrl + Shift + S: 查看状态
    if (event.ctrlKey && event.shiftKey && event.key === 'S') {
        event.preventDefault();
        if (fishModeService) {
            const state = fishModeService.getState();
            console.log('Current state:', state);
        }
    }
});